<template>
	<div id="app">
		<span>{{result}}</span>
		<br>
		<input type="file" accept="image/png, image/jpeg" @change="changeFile"> </input>
		<br>
		<img id="myimg" v-show="false">
		<canvas id="mycanvas"></canvas>
	</div>
</template>

<script>
	import jsQR from "jsqr"
	export default {
		data() {
			return {
				result: "",
			}
		},
		methods: {
			changeFile(e) {
				var that = this;
				that.result = "请上传二维码";
				console.dir(e.target.files[0].name);
				var fileReader = new FileReader();

				fileReader.onload = function(event) {
					var data = event.target.result;
					// console.dir(data);
					var img = document.getElementById("myimg");
					img.src = data;

					img.onload = function() {
						var mycanvas = document.getElementById("mycanvas");
						var ctx = mycanvas.getContext("2d");
						// canvas 的width/height重新设置的时候会清空画布
						mycanvas.width = img.width;
						mycanvas.height = img.height;

						ctx.drawImage(img, 0, 0);
						var imageData = ctx.getImageData(0, 0, img.width, img.height);
						console.log(imageData);
						
						const code = jsQR(imageData.data, imageData.width, imageData.height, {
							inversionAttempts: "dontInvert",
						});
						if (code) {
							console.log(code.data);
						} else {
							console.log("识别错误");
						}
						that.result = code.data;
					}
				}
				fileReader.readAsDataURL(e.target.files[0]);
			}
		}
	}
</script>
<style>

</style>
